package com.sky.server.impl;

import com.sky.context.MyThrowLocal;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.server.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private HttpServletRequest request;
    @Override
    public List<AddressBook> list() {
        Long userId = MyThrowLocal.getCurrentId();
        return addressBookMapper.list(userId);
    }

    @Override
    public void add(AddressBook addressBook) {
        Long userId = MyThrowLocal.getCurrentId();
        addressBook.setUserId(userId);

        addressBookMapper.add(addressBook);
    }

    @Override
    public AddressBook getDefault() {
        Long userId = MyThrowLocal.getCurrentId();
        //构造查询条件
        //todo  因为默认的地址查询条件is_default是可以写死到sql中的所以下面的代码可以优化
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        return addressBookMapper.getDefault(addressBook);
    }

    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        Long userId = MyThrowLocal.getCurrentId();
        // todo
        //  这里需要先把当前用户的所有地址修改为非默认地址
        AddressBook paras=new AddressBook();
        paras.setUserId(userId);
        paras.setIsDefault(0);
        log.info("paras:{}",paras);
        addressBookMapper.cleanDefault(paras);
        //再单独设置传入的地址为默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.setDefault(addressBook);
    }
}
